<?php

App::import('Vendor', 'PhpCaptcha', array('file' => 'phpcaptcha' . DS . 'php-captcha.inc.php'));

/**
 * Captcha Component using PhpCaptcha vendor
 * 
 * @author OanhNN
 */
class CaptchaComponent extends Component {

    /**
     * @var Controller
     */
    public $controller;

    /**
     * Initialize The Component
     * Called before the Controller::beforeFilter().
     * @param Controller $controller
     * @return void
     */
    public function initialize(Controller $controller) {
        $this->controller = $controller;
    }

    /**
     * Called after the Controller::beforeFilter() and before the controller action
     * @param Controller $controller
     * @return void
     */
    public function startup(Controller $controller) {
        
    }

    /**
     * Called before the Controller::beforeRender(), and before 
     * the view class is loaded, and before Controller::render()
     * @param Controller $controller
     * @return void
     */
    public function beforeRender(Controller $controller) {
        
    }

    /**
     * Called after Controller::render() and before the output is printed to the browser.
     * @param Controller $controller
     * @return void
     */
    public function shutdown(Controller $controller) {
        
    }

    /**
     * Create captcha image
     */
    public function image() {

        $imagesPath = WWW_ROOT . 'files' . DS . 'fonts' . DS;
        $aFonts = array(
            $imagesPath . 'VeraBd.ttf',
            $imagesPath . 'VeraIt.ttf',
            $imagesPath . 'Vera.ttf'
        );

        $oVisualCaptcha = new PhpCaptcha($aFonts, 200, 30);
        $oVisualCaptcha->UseColour(true);
        $oVisualCaptcha->SetNumChars(6);
        $oVisualCaptcha->SetNumLines(5);
        $oVisualCaptcha->Create();
    }

    /**
     * Create captcha audio
     */
    public function audio() {
        $oAudioCaptcha = new AudioPhpCaptcha('/usr/bin/flite', '/tmp/');
        $oAudioCaptcha->Create();
    }

    /**
     * Check captcha
     */
    public function check($userCode, $caseInsensitive = true) {
        if ($caseInsensitive) {
            $userCode = strtoupper($userCode);
        }
        if (!empty($_SESSION[CAPTCHA_SESSION_ID]) && $userCode == $_SESSION[CAPTCHA_SESSION_ID]) {
            // clear to prevent re-use 
            unset($_SESSION[CAPTCHA_SESSION_ID]);
            return true;
        }
        else
            return false;
    }

}

?>